package cn.itrip.auth.controller;

import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 用户管理控制器
 *
 * @author hduser
 */
@Api(tags = "用户功能模块")
@Controller
@RequestMapping(value = "/api")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisAPI redisAPI;
    @Resource
    private SimpleMailMessage activationMailMessage;
    @Resource
    private JavaMailSenderImpl mailSender;

    @ApiIgnore
    @RequestMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    /**
     * 使用邮箱注册
     *
     * @param userVO
     * @return
     */
    @ApiOperation(value = "邮箱注册")
    @RequestMapping(value = "/doregister", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    Dto doRegister(@ApiParam(required = true, value = "注册用户") @RequestBody ItripUserVO userVO) {
        if (validEmail(userVO.getUserCode())) {
            //创建邮件发送服务器
            activationMailMessage.setTo(userVO.getUserCode());
            UUID uuid = UUID.randomUUID();
            activationMailMessage.setText("你的验证码是：" + uuid.toString());
            //发送邮件
            mailSender.send(activationMailMessage);
            ItripUser itripUser = new ItripUser();
            itripUser.setUserCode(userVO.getUserCode());
            itripUser.setUserName(userVO.getUserName());
            itripUser.setUserPassword(MD5.getMd5(userVO.getUserPassword(), 32));
            try {
                if (null != userService.userRegister(itripUser)) {
                    redisAPI.set(userVO.getUserCode(), 30 * 60, uuid.toString());
                    return DtoUtil.returnSuccess();
                } else {
                    return DtoUtil.returnSuccess(ErrorCode.AUTH_AUTHENTICATION_FAILED);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnSuccess(e.getMessage(), "false");
            }
        } else {
            return DtoUtil.returnFail("邮箱格式不正确！", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }
    }

    /**
     * 使用手机注册
     *
     * @param userVO
     * @return
     */
    @ApiOperation(value = "手机注册")
    @RequestMapping(value = "/registerbyphone", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    Dto registerByPhone(
            @ApiParam(required = true, value = "注册用户") @RequestBody ItripUserVO userVO) {
        if (validPhone(userVO.getUserCode())) {
            Integer smsNum = TemplateSMS.sendSMS();
            String userCode = userVO.getUserCode();
            redisAPI.set(userCode, 5 * 60, smsNum.toString());
            ItripUser itripUser = new ItripUser();
            itripUser.setUserCode(userVO.getUserCode());
            itripUser.setUserName(userVO.getUserName());
            itripUser.setUserPassword(MD5.getMd5(userVO.getUserPassword(), 32));
            try {
                Integer register = userService.userRegister(itripUser);
                if (register == -1) {
                    return DtoUtil.returnFail("用户已存在！", ErrorCode.AUTH_USER_ALREADY_EXISTS);
                } else if (register > 0) {
                    return DtoUtil.returnSuccess("注册成功！");
                } else {
                    return DtoUtil.returnFail("手机注册失败！", ErrorCode.AUTH_UNKNOWN);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_AUTHENTICATION_FAILED);
            }
        } else {
            return DtoUtil.returnFail("手机格式不正确！", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }

    }

    /**
     * 检查用户是否已注册
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/ckusr", method = RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "检查用户是否存在")
    public @ResponseBody
    Dto checkUser(@RequestParam String name) {
        Map<String, Object> param = new HashMap<>(10);
        param.put("userCode", name);
        try {
            Integer i = userService.ckusrUser(param);
            if (i > 0) {
                return DtoUtil.returnFail("用户已存在！", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            } else {
                return DtoUtil.returnSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }


    @ApiOperation(value = "激活用户")
    @RequestMapping(value = "/activate", method = RequestMethod.PUT, produces = "application/json")
    public @ResponseBody
    Dto activate(
            @RequestParam String user,
            @RequestParam String code) {
        Dto dto = new Dto();
        String val = redisAPI.get(user);
        if (val != null && val.equals(code)) {
            try {
                userService.userActivate(user);
                dto.setSuccess("true");
            } catch (Exception e) {
                e.printStackTrace();
                dto.setSuccess("false");
                dto.setErrorCode(e.getMessage());
            }
        } else {
            dto.setSuccess("false");
        }
        return dto;
    }


	/*@RequestMapping(value="/validatephone",method=RequestMethod.PUT,produces= "application/json")
	public @ResponseBody Dto validatePhone(
			@RequestParam String user,
			@RequestParam String code){

		return null;
	}*/


    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email) {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }

    /**
     * 验证是否合法的手机号
     *
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex = "^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }
}



